﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using PH.Model.Services;
using PH.Logic.Services;
using PH.Logic.Accounts;
using PH.Model.Accounts;
using Newtonsoft.Json.Linq;
namespace PH.Web.Management.Areas.Services.Controllers
{
    public class ServiceBase : ApiController
    {
        private string Token
        {
            get
            {
                return "d7823c614d065e4d2209158d245ab841";
            }
        }

        /// <summary>
        /// 合法性认证
        /// </summary>
        /// <param name="signature">签名</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <returns></returns>
        private bool Auth(string signature, string timestamp, string nonce, string token = null)
        {
            token = token ?? Token;
            var arr = new[] { token, timestamp, nonce }.OrderBy(p => p).ToArray();
            string str = string.Join("", arr);
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var data = Encoding.Default.GetBytes(str);
            var hashdata = sha1.ComputeHash(data);
            string realsignature = BitConverter.ToString(hashdata).Replace("-", "").ToLower();
            if (signature == realsignature && !SignatureLogic.Exist(signature))
            {
                SignatureLogic.CreateNew(new SignatureModel() { Token=signature });
                return true;
            }
            return false;
        }
        /// <summary>
        /// 访问认证 
        /// </summary>
        protected void Authorize()
        {
            var signature = PH.Web.Global.WebContext.Request["signature"];
            var timestamp = PH.Web.Global.WebContext.Request["timestamp"];
            var nonce = PH.Web.Global.WebContext.Request["nonce"];
            if (!Auth(signature, timestamp, nonce))
                throw new Utils.PhException("非法访问");
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected UserModel GetUserByToken(JObject request)
        {
             var tokenstr = request.Value<string>("token");
             if (!string.IsNullOrEmpty(tokenstr))
             {
                 var token = new Guid(tokenstr);
                 var user = UserLogic.GetUserByToken(token);
                 return user;
             }
             else
                 throw new Utils.PhException("请提供token");
        }
    }
}